package com.example.smssender;

import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.card.MaterialCardView;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 发送记录详情页面
 */
public class SmsSendRecordDetailActivity extends AppCompatActivity {
    
    private SmsSendRecord record;
    private DataManager dataManager;
    
    private TextView tvDateTime;
    private TextView tvTotalContacts;
    private TextView tvSuccessCount;
    private TextView tvFailCount;
    private TextView tvSuccessRate;
    private TextView tvMessageContent;
    private TextView tvTemplateName;
    private MaterialCardView cardSuccessContacts;
    private RecyclerView rvSuccessContacts;
    private MaterialCardView cardFailedContacts;
    private RecyclerView rvFailedContacts;
    private Button btnDelete;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sms_send_record_detail);
        
        dataManager = DataManager.getInstance(this);
        
        // 获取记录ID
        String recordId = getIntent().getStringExtra("record_id");
        if (recordId == null) {
            Toast.makeText(this, "记录ID不存在", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        
        // 获取记录
        record = dataManager.getSendRecordById(recordId);
        if (record == null) {
            Toast.makeText(this, "记录不存在", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        
        // 设置工具栏
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
        
        // 初始化视图
        initViews();
        
        // 填充数据
        fillData();
    }
    
    private void initViews() {
        tvDateTime = findViewById(R.id.tvDateTime);
        tvTotalContacts = findViewById(R.id.tvTotalContacts);
        tvSuccessCount = findViewById(R.id.tvSuccessCount);
        tvFailCount = findViewById(R.id.tvFailCount);
        tvSuccessRate = findViewById(R.id.tvSuccessRate);
        tvMessageContent = findViewById(R.id.tvMessageContent);
        tvTemplateName = findViewById(R.id.tvTemplateName);
        cardSuccessContacts = findViewById(R.id.cardSuccessContacts);
        rvSuccessContacts = findViewById(R.id.rvSuccessContacts);
        cardFailedContacts = findViewById(R.id.cardFailedContacts);
        rvFailedContacts = findViewById(R.id.rvFailedContacts);
        btnDelete = findViewById(R.id.btnDelete);
        
        // 删除按钮点击事件
        btnDelete.setOnClickListener(v -> deleteRecord());
    }
    
    private void fillData() {
        if (record == null) {
            return;
        }
        
        // 基本信息
        tvDateTime.setText(record.getDateTime());
        tvTotalContacts.setText(String.valueOf(record.getTotalContacts()));
        tvSuccessCount.setText(String.valueOf(record.getSuccessCount()));
        tvFailCount.setText(String.valueOf(record.getFailCount()));
        
        DecimalFormat df = new DecimalFormat("#.##");
        // 防止除零错误，确保有值
        double successRate = record.getTotalContacts() > 0 ? record.getSuccessRate() : 0.0;
        tvSuccessRate.setText(df.format(successRate) + "%");
        
        // 短信内容
        String content = record.getMessageContent();
        if (content != null && !content.isEmpty()) {
            tvMessageContent.setText(content);
        } else {
            tvMessageContent.setText("（无内容）");
        }
        
        // 模板信息
        String templateName = record.getTemplateName();
        if (templateName != null && !templateName.isEmpty()) {
            tvTemplateName.setText("使用模板: " + templateName);
            tvTemplateName.setVisibility(View.VISIBLE);
        } else {
            tvTemplateName.setVisibility(View.GONE);
        }
        
        // 成功联系人列表
        List<ContactInfo> successContacts = record.getSuccessContacts();
        if (successContacts != null && !successContacts.isEmpty()) {
            cardSuccessContacts.setVisibility(View.VISIBLE);
            setupSuccessContactsList(successContacts);
        } else {
            cardSuccessContacts.setVisibility(View.GONE);
        }
        
        // 失败详情
        List<FailedContact> failedContacts = record.getFailedContacts();
        if (failedContacts != null && !failedContacts.isEmpty()) {
            cardFailedContacts.setVisibility(View.VISIBLE);
            setupFailedContactsList(failedContacts);
        } else {
            cardFailedContacts.setVisibility(View.GONE);
        }
    }
    
    private void setupSuccessContactsList(List<ContactInfo> successContacts) {
        if (successContacts == null || successContacts.isEmpty()) {
            return;
        }
        rvSuccessContacts.setLayoutManager(new LinearLayoutManager(this));
        
        // 创建简单的适配器显示成功联系人
        List<ContactInfoItem> items = new ArrayList<>();
        for (ContactInfo contact : successContacts) {
            if (contact != null) {
                items.add(new ContactInfoItem(contact));
            }
        }
        
        if (!items.isEmpty()) {
            SuccessContactAdapter adapter = new SuccessContactAdapter(items);
            rvSuccessContacts.setAdapter(adapter);
        }
    }
    
    private void setupFailedContactsList(List<FailedContact> failedContacts) {
        if (failedContacts == null || failedContacts.isEmpty()) {
            return;
        }
        rvFailedContacts.setLayoutManager(new LinearLayoutManager(this));
        
        // 创建简单的适配器显示失败联系人
        List<FailedContactItem> items = new ArrayList<>();
        for (FailedContact fc : failedContacts) {
            if (fc != null) {
                items.add(new FailedContactItem(fc));
            }
        }
        
        if (!items.isEmpty()) {
            FailedContactAdapter adapter = new FailedContactAdapter(items);
            rvFailedContacts.setAdapter(adapter);
        }
    }
    
    private void deleteRecord() {
        if (record == null || record.getId() == null) {
            Toast.makeText(this, "记录信息无效", Toast.LENGTH_SHORT).show();
            return;
        }
        new AlertDialog.Builder(this)
                .setTitle("删除记录")
                .setMessage("确定要删除这条发送记录吗？")
                .setPositiveButton("删除", (dialog, which) -> {
                    dataManager.deleteSendRecord(record.getId());
                    Toast.makeText(this, "记录已删除", Toast.LENGTH_SHORT).show();
                    finish();
                })
                .setNegativeButton("取消", null)
                .show();
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    
    // 简单的成功联系人适配器
    private static class ContactInfoItem {
        ContactInfo contact;
        
        ContactInfoItem(ContactInfo contact) {
            this.contact = contact;
        }
    }
    
    private static class SuccessContactAdapter extends RecyclerView.Adapter<SuccessContactAdapter.ViewHolder> {
        private List<ContactInfoItem> items;
        
        SuccessContactAdapter(List<ContactInfoItem> items) {
            this.items = items;
        }
        
        @Override
        public ViewHolder onCreateViewHolder(android.view.ViewGroup parent, int viewType) {
            View view = android.view.LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_success_contact, parent, false);
            return new ViewHolder(view);
        }
        
        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            ContactInfoItem item = items.get(position);
            if (item != null && item.contact != null) {
                holder.tvName.setText(item.contact.getDisplayName() != null ? item.contact.getDisplayName() : "未知");
                holder.tvPhone.setText(item.contact.getPhoneNumber() != null ? item.contact.getPhoneNumber() : "");
            } else {
                holder.tvName.setText("未知");
                holder.tvPhone.setText("");
            }
        }
        
        @Override
        public int getItemCount() {
            return items != null ? items.size() : 0;
        }
        
        static class ViewHolder extends RecyclerView.ViewHolder {
            TextView tvName;
            TextView tvPhone;
            
            ViewHolder(View itemView) {
                super(itemView);
                tvName = itemView.findViewById(R.id.tvName);
                tvPhone = itemView.findViewById(R.id.tvPhone);
            }
        }
    }
    
    // 简单的失败联系人适配器
    private static class FailedContactItem {
        FailedContact contact;
        
        FailedContactItem(FailedContact contact) {
            this.contact = contact;
        }
    }
    
    private static class FailedContactAdapter extends RecyclerView.Adapter<FailedContactAdapter.ViewHolder> {
        private List<FailedContactItem> items;
        
        FailedContactAdapter(List<FailedContactItem> items) {
            this.items = items;
        }
        
        @Override
        public ViewHolder onCreateViewHolder(android.view.ViewGroup parent, int viewType) {
            View view = android.view.LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_failed_contact, parent, false);
            return new ViewHolder(view);
        }
        
        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            FailedContactItem item = items.get(position);
            if (item != null && item.contact != null) {
                holder.tvName.setText(item.contact.getDisplayName() != null ? item.contact.getDisplayName() : "未知");
                holder.tvPhone.setText(item.contact.getPhoneNumber() != null ? item.contact.getPhoneNumber() : "");
                String errorMsg = item.contact.getErrorMessage();
                holder.tvError.setText(errorMsg != null && !errorMsg.isEmpty() ? errorMsg : "未知错误");
            } else {
                holder.tvName.setText("未知");
                holder.tvPhone.setText("");
                holder.tvError.setText("未知错误");
            }
        }
        
        @Override
        public int getItemCount() {
            return items != null ? items.size() : 0;
        }
        
        static class ViewHolder extends RecyclerView.ViewHolder {
            TextView tvName;
            TextView tvPhone;
            TextView tvError;
            
            ViewHolder(View itemView) {
                super(itemView);
                tvName = itemView.findViewById(R.id.tvName);
                tvPhone = itemView.findViewById(R.id.tvPhone);
                tvError = itemView.findViewById(R.id.tvError);
            }
        }
    }
}

